package com.example.mall.user.svc.infr.constants;

import com.example.mall.common.constants.BaseEnum;
import com.example.mall.common.constants.CodeEnum;
import com.example.mall.common.exception.BizException;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.fasterxml.jackson.databind.ser.std.StdSerializer;
import lombok.AllArgsConstructor;
import lombok.Getter;

import java.io.IOException;
import java.util.Optional;

/**
 * 登陆模式
 *
 * @author Mickey
 * @since 2022/4/17
 **/
@Getter
@AllArgsConstructor
@JsonSerialize(using = LoginModeType.Serializer.class)
public enum LoginModeType implements BaseEnum<LoginModeType> {

    USERNAME_PASSWORD(0, "用户名密码登陆"),
    MOBILE(1, "手机登陆"),
    ;

    private final Integer code;
    private final String name;

    public static LoginModeType of(Integer code) {
        return Optional
                .ofNullable(BaseEnum.parseByCode(LoginModeType.class, code))
                .orElseThrow(() -> new BizException(CodeEnum.FAIL));
    }

    @JsonCreator
    public static LoginModeType create(Integer code) {
        return of(code);
    }

    public static class Serializer extends StdSerializer<LoginModeType> {
        public Serializer() {
            super(LoginModeType.class);
        }

        public void serialize(LoginModeType type, JsonGenerator gen, SerializerProvider p) throws IOException {
            gen.writeNumber(type.getCode());
        }
    }

}
